// pages/find/find.js
var app = getApp();
var WebIM = require('../../utils/WebIM.js').default
let disp = require("../../utils/broadcast");
const {
  post
} = require("../../utils/util")
let imgurl = app.globalData.imgurl;
let testAddr = app.globalData.testAddr;
let det_arr = []
// http://112.74.53.122:8088/img/guest/bg.jpg
Page({
  /**
   * delBtnWidth: 删除按钮的宽度单位
   * arr: 循环的mock数据
   * startX: 收支触摸开始滑动的位置
   */
  data: {
    delBtnWidth: 180,
    startX: "",
    arr: [],
    search_btn: true,
    search_chats: false,
    show_mask: false,
    yourname: "",
    unReadSpot: false,
    head_bg: imgurl + '/guest/bg.jpg'
  },
  onLoad: function(options) {
    det_arr = [];
    let me = this;
    disp.on("em.xmpp.unreadspot", function(count) {
      me.setData({
        arr: me.getChatList(),
        unReadSpot: count > 0
      });
    });
    // 页面初始化 options为页面跳转所带来的参数
    this.initEleWidth();
  },
  into_inform: function() {
    var myName = wx.getStorageSync("list").guestid
    wx.navigateTo({
      url: "../detail/inform/inform?myName=" + myName
    });
  },
  //  通讯录列表
  go_chat_list: function() {
    wx.navigateTo({
      url: '../detail/maillist/maillist',
    })
  },
  onReady: function() {

  },
  getChatList() {
    var that = this;
    var array = [];
    var member = wx.getStorageSync("member");
    var myName = wx.getStorageSync("myUsername");
    for (let i = 0; i < member.length; i++) {
      let newChatMsgs = wx.getStorageSync(member[i].name + myName) || [];
      let historyChatMsgs = wx.getStorageSync("rendered_" + member[i].name + myName) || [];
      let curChatMsgs = historyChatMsgs.concat(newChatMsgs);
      if (curChatMsgs.length) {
        let lastChatMsg = curChatMsgs[curChatMsgs.length - 1];
        lastChatMsg.unReadCount = newChatMsgs.length;
        if (lastChatMsg.unReadCount > 10) {
          lastChatMsg.unReadCount = "...";
        }
        array.push(lastChatMsg);
      }
    }
    for (var i = 0; i < array.length; i++) {
      array[i].time = array[i].time.slice(0, 10)
      that.detail(array[i].info.to, that.callback)
    }
    return array;
  },
  callback(list) {
    var that = this
    var oldArr = that.data.arr
    for (var i = 0; i < oldArr.length; i++) {
      if (list.guestid == oldArr[i].username) {
        oldArr[i].imgUrl = imgurl + 'guest/' + list.imgUrl
        oldArr[i].name = list.guestName
      }
    }
    this.setData({
      arr: oldArr
    })
  },
  //  根据guestid查询详细信息
  detail: function(id, callback) {
    var that = this
    var arr;
    app.util.request({
      url: testAddr + "/Guest/GetInfoByID?guestID=" + id,
      method: "POST",
      data: {},
      success: function(res) {
        arr = res.data
        that.callback(arr)
      },
      fail: function(res) {

      },
      complete: function(res) {
        wx.hideLoading()
      },
    });
  },
  
  onShow: function() {
    det_arr = []
    this.setData({
      arr: this.getChatList(),
      unReadSpot: getApp().globalData.unReadSpot,
    });
    if (wx.getStorageSync("list")) {
      var info = wx.getStorageSync("list")
      app.imloign(info.guestid, info.chatPwd)
    } else {
      app.userLogin()
    }
  },

  openSearch: function() {
    this.setData({
      search_btn: false,
      search_chats: true,
      show_mask: true
    });
  },

  cancel: function() {
    this.setData({
      search_btn: true,
      search_chats: false,
      show_mask: false
    });
  },


  close_mask: function() {
    this.setData({
      search_btn: true,
      search_chats: false,
      show_mask: false
    });
  },

  tab_setting: function() {
    wx.redirectTo({
      url: "../detail/settings/settings"
    });
  },

  into_chatRoom: function(event) {
    var my = wx.getStorageSync("myUsername");
    var nameList = {
      myName: my,
      your: event.currentTarget.dataset.username,
      head: event.currentTarget.dataset.head
    };
    wx.navigateTo({
      url: "../detail/chatroom/chatroom?username=" + JSON.stringify(nameList)
    });
  },


  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
  touchS: function(e) {
    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function(e) {
    if (e.touches.length == 1) {
      //手指移动时水平方向位置
      var moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var txtStyle = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，说明向右滑动，文本层位置不变
        txtStyle = "left:0px";
      } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "left:-" + delBtnWidth + "px";
        }
      }
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var arr = this.data.arr;
      arr[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        arr: arr
      });
    }
  },
  touchE: function(e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var arr = this.data.arr;
      arr[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        arr: arr
      });
    }
  },
  //获取元素自适应后的实际宽度
  getEleWidth: function(w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2); //以宽度750px设计稿做宽度的自适应
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error
    }
  },
  initEleWidth: function() {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },
  //点击删除按钮事件
  // delItem: function (e) {
  //   //获取列表中要删除项的下标
  //   var index = e.currentTarget.dataset.index;
  //   var arr = this.data.arr;
  //   //移除列表中下标为index的项
  //   arr.splice(index, 1);
  //   //更新列表的状态
  //   this.setData({
  //     arr: arr
  //   });
  // },
  del_chat: function(event) {
    var that = this
    var nameList = {
      your: event.currentTarget.dataset.username
    };
    var myName = wx.getStorageSync("myUsername");
    //获取列表中要删除项的下标
    var index = event.currentTarget.dataset.index;
    var arr = this.data.arr;
    var currentPage = getCurrentPages();
    wx.showModal({
      title: "删除该聊天记录",
      confirmText: "删除",
      success: function(res) {
        if (res.confirm) {
          wx.setStorageSync(nameList.your + myName, "");
          wx.setStorageSync("rendered_" + nameList.your + myName, "");
          if (currentPage[0]) {
            currentPage[0].onShow();
          }
          disp.fire("em.chat.session.remove");
          //移除列表中下标为index的项
          arr.splice(index, 1);
          //更新列表的状态
          that.setData({
            arr: arr
          });
        }
      },
      fail: function(err) {}
    });
  },
})